<template>
  <!--列表-->
  <section>
    <el-form :inline="true" :model="inviteQuery" class="toolbar"
             style="text-align: left;margin-top: 20px">
      <el-row>
        <el-col :span="8">
          <el-form-item label="关键字">
            <el-input v-model="inviteQuery.keyword" placeholder="请输入昵称进行查询"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="onSearch">查询</el-button>
            <el-button type="success" @click="exportExcel">按需导出</el-button>
            <el-link type="warning" href="https://test.scoremaster.top/apis/admin/adminLucky/exportExcel" target="_blank"
                     style="margin-left: 20px">导出全部
            </el-link>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item>
            <div class="block">
              <el-date-picker
                  v-model="value"
                  type="daterange"
                  align="right"
                  unlink-panels
                  @change="handleDateChange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="pickerOptions">
              </el-date-picker>
            </div>
          </el-form-item>
          <el-form-item>总计 {{totalCount}} 条数据</el-form-item>
        </el-col>
      </el-row>

    </el-form>
    <el-table :data="listDatas" highlight-current-row row-key="id" v-loading="listLoading"
              @selection-change="selsChange"
              style="width: 100%;" element-loading-text="拼命加载中">
      <el-table-column type="selection" width="55" :reserve-selection="true">
      </el-table-column>
      <el-table-column type="index" width="60" label="编号">
      </el-table-column>
      <el-table-column prop="invitedCode" label="邀请码" width="300">
      </el-table-column>
      <el-table-column prop="count2" label="邀请次数" width="100" sortable>
      </el-table-column>
      <el-table-column prop='effectiveCount' label="有效邀请次数" width="130" sortable>
      </el-table-column>
      <el-table-column prop="parentId" label="邀请者Id" width="120">
      </el-table-column>
      <el-table-column prop="data" label="创建日期" width="150" sortable>
      </el-table-column>
      <el-table-column prop="clickCount" label="链接被点击次数" width="120">
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条-->
    <el-col :span="24" class="toolbar">
      <el-popconfirm
          confirmButtonText='忍心抛弃'
          cancelButtonText='再给一次机会'
          icon="el-icon-info"
          iconColor="red"
          title="你确定要离我而去？"
          @confirm="batchRemove"
      >
        <el-button type="danger" slot="reference" :disabled="this.sels.length===0">批量删除</el-button>
      </el-popconfirm>
      <el-pagination layout="total, sizes, prev, pager, next, jumper"
                     :page-sizes="sizes"
                     @current-change="handleCurrentChange"
                     @size-change="handleSizeChange"
                     :current-page="currentPage"
                     :page-size="pageSize" :total="totalCount" style="float:right;">
      </el-pagination>
    </el-col>

    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form :model="inviteForm" :rules="inviteForm" ref="inviteForm">
        <el-form-item label="邀请次数" :label-width="formLabelWidth" prop="name">
          <el-input type="number" min="0" v-model="inviteForm.count2"></el-input>
        </el-form-item>
        <el-form-item label="有效邀请次数" :label-width="formLabelWidth">
          <el-input type="number"  min="0"  v-model="inviteForm.effectiveCount"></el-input>
        </el-form-item>
        <el-form-item label="邀请码" :label-width="formLabelWidth">
          <el-input type="text" v-model="inviteForm.invitedCode" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="邀请者Id" :label-width="formLabelWidth">
          <el-input type="text" v-model="inviteForm.parentId" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="创建日期" :label-width="formLabelWidth">
          <el-input type="text" v-model="inviteForm.data" :disabled="true"></el-input>
        </el-form-item>
        <el-form-item label="链接被点击次数" :label-width="formLabelWidth">
          <el-input type="text" v-model="inviteForm.clickCount" :disabled="true"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="onSubmit" :loading="addLoading">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog :title="title" :visible.sync="dialogProgress" style="text-align: center">
      <el-progress type="circle" :percentage="num" :status="success"></el-progress>
    </el-dialog>

  </section>

</template>

<script>

export default {
  data() {
    return {
      success: "",
      num: null,
      addLoading: false,
      listDatas: [],
      listLoading: true,
      sels: [],
      sizes: [10, 20, 50, 100],
      pageSize: 20,
      currentPage: 1,
      totalCount: 0,
      inviteQuery: {
        keyword: '',
      },
      formLabelWidth: '120px',
      title: "新增",
      inviteForm: {
        id: null,
        count2: '',
        effectiveCount: '',
        invitedCode: "",
        parentId: '',
        data:'',
        clickCount:'',
      },
      dialogProgress: false,
      dialogFormVisible: false,
      dialogExportExcel: false,
      value: '',
      formattedStartDate:"",
      formattedEndDate:"",
      pickerOptions: {
        shortcuts: [{
          text: '最近一周',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近一个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
            picker.$emit('pick', [start, end]);
          }
        }, {
          text: '最近三个月',
          onClick(picker) {
            const end = new Date();
            const start = new Date();
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
            picker.$emit('pick', [start, end]);
          }
        }]
      },
    }
  },
  methods: {
    executeQuery(startDate, endDate) {
      // 在这里执行您的查询逻辑
      console.log(`Querying from ${startDate} to ${endDate}`);
      this.loadListData()
    },
    handleDateChange() {
      // `value` 是一个数组，包含选中的开始和结束日期
      if (this.value && this.value.length === 2) {
        const [startDate, endDate] = this.value;
        // 格式化日期
        this.formattedStartDate = this.formatDate(startDate);
        this.formattedEndDate = this.formatDate2(endDate);
        // 执行查询方法
        this.executeQuery(this.formattedStartDate, this.formattedEndDate);
      }

      if (!this.value || this.value.length === 0) {
        // 当选择的日期被清空时，设置value为空数组
        this.formattedStartDate = ""
        this.formattedEndDate = ""
        this.executeQuery(this.formattedStartDate, this.formattedEndDate)
      }
    },
    formatDate(startDate) {
      const formatPart = value => (value + 1).toString().padStart(2, '0');
      let startFormatted = `${startDate.getFullYear()}-${formatPart(startDate.getMonth())}-${formatPart(startDate.getDate()-1)} 00:00:00`;
      return `${startFormatted}`;
    },
    formatDate2(endDate) {
      const formatPart = value => (value + 1).toString().padStart(2, '0');
      let endFormatted = `${endDate.getFullYear()}-${formatPart(endDate.getMonth())}-${formatPart(endDate.getDate() -1)} 23:59:59`;
      return `${endFormatted}`;
    },
    //批量删除
    batchRemove() {
      //把对象数组转成 id数组
      let deptIds = this.sels.map(function (obj, index, array) {
        return obj.id;
      })
      this.$http.delete("/admin/invite/deleteList", {data: deptIds}).then(res => {
        let {msg, success} = res.data
        if (success) {
          //操作成功   给一条提示
          this.$message.success("删除成功");
        } else {
          //操作失败  给一条失败的提示
          this.$message.error("操作失败")
        }
        this.loadListData();
      })
    },
    exportExcel() {
      console.log(this.sels)
      if (this.sels.length != 0) {
        this.title = "正在下载..."
        this.dialogProgress = true;
        this.num = 0;
        this.$http.put("/admin/invite/exportMore", this.sels, {responseType: 'blob'}).then(res => {
          this.num = 30;
          let resBlob = new Blob([res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
          let a = document.createElement("a");
          let url = URL.createObjectURL(resBlob);
          this.num = 50;
          //将url赋值给a标签的href属性
          a.href = url;
          //下载的文件的文件名
          a.download = "管理员数据表.xlsx";
          this.num = 70;
          //触发click事件执行下载
          a.click();
          //要记得回收URL
          URL.revokeObjectURL(url);
          this.num = 100;
          this.success = "success";
          this.title = "下载完成!"
        })
      } else {
        this.$message.error("没有选择数据")
      }

    },
    loadListData() {
      //2、组装分页数据
      let param = {
        keyword: this.inviteQuery.keyword,
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        start:this.formattedStartDate,
        end:this.formattedEndDate
      }
      this.$http.post("/admin/invite", param).then(res => {
        let {data, success, msg} = res.data;
        if (success) {
          this.listDatas = data.rows;
          this.totalCount = data.total;
          //关闭加载效果
          this.listLoading = false;
        } else {
          this.$message.error(msg)
        }
      })
    },
    selsChange: function (sels) {
      this.sels = sels;
      console.log(this.sels)
    },
    //删除
    handleDel: function (index, row) {
      this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.delete("/admin/invite/" + row.id).then(res => {
          this.listLoading = false;
          if (res.data.success) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
          } else {
            this.$message({
              type: 'error',
              message: '删除失败!'
            });
          }
          if (this.totalCount / this.pageSize)
            this.loadListData();
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    //显示编辑界面
    handleEdit: function (index, row) {
      //1、获取当前行的数据
      //2、数据回显
      //3、打开弹出框
      this.title = '修改';
      this.inviteForm = row;
      this.dialogFormVisible = true;
    },
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
      this.pageSize = val;
      this.currentPage = 1;
      this.loadListData();
    },
    handleCurrentChange(val) {
      //val 就是当前页的页码
      console.log(`当前页: ${val}`);
      this.currentPage = val;
      this.loadListData();
    },
    onSearch() {
      this.listLoading = true;
      this.loadListData();
    },
    onSubmit() {
      this.$refs.inviteForm.validate((valid) => {
        if (valid) {
          this.addLoading = true;
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.$http.put('/admin/invite/saveOrUpdate', this.inviteForm).then(res => {
              this.addLoading = false;
              if (res.data.success) {
                this.$message.success("添加操作成功！");
              } else {
                this.$message.error("添加操作失败！");
              }
              this.dialogFormVisible = false;
              this.loadListData();
            });
          }).catch(() => {
            this.addLoading = false;
            this.$message.info("取消操作");
          })
        }
      });
    },
  },
  mounted() {
    //加载完毕以后调用获取列表数据的方法
    this.loadListData();
  }
}
</script>

<style scoped>

</style>